import { _decorator, BoxCollider2D, Collider2D, Component, Contact2DType, IPhysics2DContact, Label, Node, Vec3 } from 'cc';
import { ballController } from './ballControl';
import { audioControl } from './audioControl';
import { Ikun } from './IkunControl';
const { ccclass, property } = _decorator;

@ccclass('heiziControl')
export class heiziControl extends Component {

  direction: boolean = false
  @property(Number)
  speed: number = 10
  isMove: boolean = true
  isDead: boolean = false
  audio: audioControl = null
  ikun: Ikun = null

  onLoad() {
    this.getComponent(BoxCollider2D).on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this)
    this.audio = this.node.getParent().getChildByName('audio').getComponent(audioControl)
    this.ikun = this.node.getParent().getChildByName('ikun').getComponent(Ikun)
  }
  start() {

  }

  update(deltaTime: number) {
    if (this.isMove && !this.isDead) {
      this.move(this.direction, deltaTime)
    }
  }
  move(dir: boolean, dt: number) {
    const { x, y, z } = this.node.position
    const moveX = dir ? x + this.speed * dt : x - this.speed * dt
    this.node.setPosition(new Vec3(moveX, y, z))
  }
  onBeginContact(self: Collider2D, other: Collider2D, contact: IPhysics2DContact) {
    //黑子撞篮球 && 篮球没在地上
    const touchedGround = other.node.getComponent(ballController)?.touchedGround
    if (other.tag === 1 && !this.isDead && touchedGround === false) {
      this.die()
    }
    //如果撞到其他的 没撞到鸡哥
    if ((other.tag == 0 || other.tag == 3) && !this.isDead) {
      this.direction = !this.direction
    }
  }
  die() {
    this.isDead = true
    this.isMove = false
    this.audio.jiVoice()
    this.ikun.updateScore()
    //暂时只能通过异步调用销毁
    this.schedule(() => {
      this.node.destroy()
    })
  }
}


